package cn.wolfcode.car.business.service.impl;

import cn.wolfcode.car.business.domain.BpmnInfo;
import cn.wolfcode.car.business.domain.Statement;
import cn.wolfcode.car.business.mapper.BpmnInfoMapper;
import cn.wolfcode.car.business.mapper.StatementMapper;
import cn.wolfcode.car.business.query.BpmnInfoQuery;
import cn.wolfcode.car.business.service.IBpmnInfoService;
import cn.wolfcode.car.common.base.page.TablePageInfo;
import cn.wolfcode.car.common.config.SystemConfig;
import cn.wolfcode.car.common.exception.BusinessException;
import cn.wolfcode.car.common.util.Convert;
import com.github.pagehelper.PageHelper;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.image.ProcessDiagramGenerator;
import org.activiti.image.impl.DefaultProcessDiagramGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.*;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.zip.ZipInputStream;

@Service
@Transactional
public class BpmnInfoServiceImpl implements IBpmnInfoService {

    @Autowired
    private BpmnInfoMapper bpmnInfoMapper;
    @Autowired
    private StatementMapper statementMapper;
    @Autowired
    private RepositoryService repositoryService;


    @Override
    public TablePageInfo<BpmnInfo> query(BpmnInfoQuery qo) {
        PageHelper.startPage(qo.getPageNum(), qo.getPageSize());
        return new TablePageInfo<BpmnInfo>(bpmnInfoMapper.selectForList(qo));
    }


    @Override
    public void save(BpmnInfo bpmnInfo) {
        bpmnInfoMapper.insert(bpmnInfo);
    }


    @Override
    public BpmnInfo get(Long id) {
        return bpmnInfoMapper.selectByPrimaryKey(id);
    }


    @Override
    public void update(BpmnInfo bpmnInfo) {
        bpmnInfoMapper.updateByPrimaryKey(bpmnInfo);
    }

    @Override
    public void deleteBatch(String ids) {
        Long[] dictIds = Convert.toLongArray(ids);
        for (Long id : dictIds) {
            bpmnInfoMapper.deleteByPrimaryKey(id);

        }
    }

    @Override
    public List<BpmnInfo> list() {
        return bpmnInfoMapper.selectAll();
    }

    @Override
    public void deploy(String bpmnPath, String bpmnType, String info) throws IOException {
        String loSrr = bpmnPath.toLowerCase();//把路径转换成小写
        Deployment deploy = null;
        //文件流 读取之前上传的流程文件                         //文件上传的路径 加上文件的路径
        FileInputStream stream = new FileInputStream(new File(SystemConfig.getProfile(), bpmnPath));
        //文件路径也是文件的名称 查看文件末尾是否等于zip
        if (loSrr.endsWith("zip")) {              //zip格式部署的方式  需要一个ZipInputStream的流
            deploy = repositoryService.createDeployment().addZipInputStream(new ZipInputStream(stream))
                    .deploy();
        } else if (loSrr.endsWith("bpmn")) {
            deploy = repositoryService.createDeployment().addInputStream(bpmnPath, stream).
                    //这里需要资源流程定义表中的resource_name 是文件的名称 等于bpmnPath
                            deploy();
        }
        if (deploy == null) {
            throw new BusinessException("部署失败");
        }

        //根据部署id 获取流程定义
        ProcessDefinition processDefinition = repositoryService.
                createProcessDefinitionQuery().deploymentId(deploy.getId())
                .latestVersion().singleResult();

        BpmnInfo bpmnInfo = new BpmnInfo();
        bpmnInfo.setBpmnName(processDefinition.getName());
        bpmnInfo.setBpmnType(bpmnType);
        bpmnInfo.setDeploymentId(deploy.getId());
        bpmnInfo.setActProcessId(processDefinition.getId());
        bpmnInfo.setActProcessKey(processDefinition.getKey());
        bpmnInfo.setDeployTime(deploy.getDeploymentTime());
        bpmnInfo.setInfo(info);
        bpmnInfoMapper.insert(bpmnInfo);


        stream.close();
    }

    @Override
    public void updateById(String info, Long id) {
        bpmnInfoMapper.updateById(info, id);
    }

    @Override
    public void delete(Long id) {
        BpmnInfo bpmnInfo = this.get(id);


        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().deploymentId(bpmnInfo.getDeploymentId())
                .latestVersion().singleResult();

        File file = new File(SystemConfig.getProfile(), processDefinition.getResourceName());
        if (file.exists()) { //判断文件是否存在
            file.delete();   //自杀
        }

        bpmnInfoMapper.deleteByPrimaryKey(id);

        //删除activiti7自己的表 删除与流程定义有关的数据
        repositoryService.deleteDeployment(bpmnInfo.getDeploymentId(), true);


    }

    @Override
    public InputStream getResoucceByType(String deploymentId, String type) {
        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().
                deploymentId(deploymentId)
                .latestVersion().singleResult();

        InputStream inputStream = null;

        if ("xml".equalsIgnoreCase(type)) {
            inputStream =  repositoryService.getResourceAsStream(deploymentId, processDefinition.getResourceName());
        }else if("png".equalsIgnoreCase(type)){
            BpmnModel model = repositoryService.getBpmnModel(processDefinition.getId());
            ProcessDiagramGenerator generator = new DefaultProcessDiagramGenerator();
            //generateDiagram(流程模型,需要高亮的节点,需要高亮的线条,后面三个参数都表示是字体)
           inputStream = generator.generateDiagram(model, Collections.EMPTY_LIST, Collections.EMPTY_LIST,
                    "宋体","宋体","宋体");
            return inputStream;
        }

        return inputStream;
    }

    @Override
    public BpmnInfo queryByType(String bpmnType) {
        return bpmnInfoMapper.queryByType("car_package");
    }
}